import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let defaultIpAddress = "ws://whhpweb.cn:9527";
let ws = webSocket.createWebSocket();

export function Ws(on:(value:string)=>void){

  function init(){// 初始化
    ws.connect(defaultIpAddress, (err: BusinessError, value: boolean) => {
      if (!err) {
        console.log("Connected successfully");
      } else {
        console.log("Connection failed. Err:" + JSON.stringify(err));
      }
    });
  }
  ws.on('open', (err: BusinessError, value: Object) => {
    console.log("on open, status:" + JSON.stringify(value));

  });
  ws.on('message', (err: BusinessError, value: string | ArrayBuffer) => {
    // console.log("on message, message:" + value);
    // 当收到服务器的`bye`消息时（此消息字段仅为示意，具体字段需要与服务器协商），主动断开连接
    on(value as string)

  });
  ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
    console.log("on close, code is " + value.code + ", reason is " + value.reason);
    // 重新链接
    init()
  });
  ws.on('error', (err: BusinessError) => {
    console.log("on error, error:" + JSON.stringify(err));
  });
  init()
  return ws
}


